﻿using System.Data.SqlClient;

namespace MyDemo.DB
{
    /// <summary>
    /// SqlBulkCopy(批量复制)使用方法
    /// http://www.cnblogs.com/scottckt/archive/2011/02/16/1955862.html
    /// </summary>
    public class SqlBulkCopyDemo
    {
        private static readonly string ConnStr1 = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = Test; Integrated Security = True; Pooling=False";
        private static readonly string ConnStr2 = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = Test2; Integrated Security = True; Pooling=False";

        /// <summary>
        /// 数据库中的表复制到另一个数据库中的表
        /// </summary>
        public static void SqlBulkCopyMethod()
        {
            try
            {    
                using (var conn1 = new SqlConnection(ConnStr1))
                {
                    using (var cmd = conn1.CreateCommand())
                    {
                        cmd.CommandText = "select * from Product";
                        cmd.CommandType = System.Data.CommandType.Text;
                        conn1.Open();

                        using (var conn2 = new SqlConnection(ConnStr2))
                        {
                            conn2.Open();
                            SqlDataReader dataReader = cmd.ExecuteReader();
                            using (var bulkCopy = new SqlBulkCopy(conn2))
                            {
                                bulkCopy.DestinationTableName = "Product";
                                bulkCopy.WriteToServer(dataReader);
                            }
                        }
                    }
                }

            }
            catch (System.Exception)
            {
                throw;
            }
        }

    }
}